import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';

@Injectable()
export class UserService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}
  // 获取所有用户数据列表(userRepository.query()方法属于typeoram)
  async findAll(): Promise<User[]> {
    return await this.userRepository.query('select * from user');
  }

  async findOne(id: number): Promise<User> {
    let user = await this.userRepository.query(
      'select * from user where id = ' + id,
    );
    if (user.length > 0) {
      return user[0];
    } else {
      throw {
        statusCode: 400,
        message: '用户名不存在',
      };
    }
  }

  async addUser(req: User): Promise<User> {
    console.log(req);
    let isHas = await this.userRepository.query(
      `select * from user where name = '${req.name}'`,
    );
    console.log(isHas);
    if (isHas.length > 0) {
      throw {
        statusCode: 400,
        message: '用户名已存在',
      };
    } else {
      const user = await this.userRepository.save(req);
      if (user) {
        return null;
      }
    }
  }

  async updateUser(req: User): Promise<User> {
    console.log(req);
    let isHas = await this.userRepository.query(
      `select * from user where id = '${req.id}'`,
    );
    console.log(isHas);
    if (isHas.length > 0) {
      const user = await this.userRepository.update(req.id, req);
      if (user) {
        return null;
      }
    } else {
      throw null;
    }
  }
}
